﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;

using System.IO;
using System.Threading;
using System.Diagnostics;
using MineLaunch.Setting;


namespace MineLaunch.Windows
{
	/// <summary>
	/// LogViewWindow.xaml の相互作用ロジック
	/// </summary>
	public partial class LogViewWindow : Window
	{
		public LogViewWindow()
		{
			InitializeComponent();
		}

		public void Run(string targetPath)
		{
			if (!Directory.Exists(targetPath))
			{
				Directory.CreateDirectory(targetPath);
			}
			var minecraftExePath = Path.Combine(Directory.GetCurrentDirectory(), SettingsGlobal.MinecraftExePath);
			var settings = SettingsMain.GetInstance().settingsMain;
			if (!File.Exists(settings.JavaPath))
			{
				MessageBox.Show("java.exeのパスが設定されていません。");
				return;
			}
			if (!File.Exists(minecraftExePath))
			{
				MessageBox.Show("Minecraft.exeが存在しません。\nMineLaunch.exeと同じフォルダに置いてください。");
				return;
			}
			var process = new Process();
			ProcessStartInfo processInfo = new ProcessStartInfo();
			processInfo.FileName = settings.JavaPath;
			if (settings.IsAutoLogin)
			{
				string passworld = Common.Common.Decrypt(settings.MinecraftPassword);
				processInfo.Arguments = String.Format("-Xms{0}m -Xmx{1}m -jar {2} {3} {4}", settings.Xms, settings.Xmx, minecraftExePath, settings.MinecraftID, passworld);
			}
			else
			{
				processInfo.Arguments = String.Format("-Xms{0}m -Xmx{1}m -jar {2}", settings.Xms, settings.Xmx, minecraftExePath);
			}
			processInfo.UseShellExecute = false;
			processInfo.EnvironmentVariables.Remove("APPDATA");
			processInfo.EnvironmentVariables.Add("APPDATA", targetPath);
			process.StartInfo = processInfo;
			processInfo.CreateNoWindow = true;
			processInfo.RedirectStandardOutput = true;
			process.OutputDataReceived+=new DataReceivedEventHandler(process_OutputDataReceived);
			process.Start();

			process.BeginOutputReadLine();

			Common.Common.ResizeMinecraftWindow();
		}

		public void process_OutputDataReceived(object sender, DataReceivedEventArgs e)
		{
			this.logTextBox.Dispatcher.BeginInvoke(new Action(() =>
			{
				this.logTextBox.AppendText(e.Data + "\n");
				this.logTextBox.ScrollToEnd();
			}));
		}
	}
}
